package com.zhang.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * User: 张
 * Date: 2024-11-05
 * Time: 15:05
 * Description:
 */

@Component
public class ToPython {
    StringBuffer stringBuffer = new StringBuffer();
    @Value("${python.pythonInterpreter}")
    private String pythonInterpreter;
    @Value("${python.pythonPath}")
    private String scriptPath;
    @Value("${operation.correct}")
    private Integer correct;

    /**
     * 3.1 初始化机器
     * @return
     */
    public String Init() throws Exception {
        return ToPythonController("init");
    }

    /**
     * 3.2 检查物料
     * @return
     */
    public String CheckMaterial() throws Exception {
        return ToPythonController("check_material");
    }

    /**
     * 3.3 控制传送带
     * @param direction
     * @param start
     * @return
     */
    public String ControlConveyorBelt(String direction,String start) throws Exception {
        Integer exitCode = null;
        try {
            String action = "control_conveyor_belt";
            ProcessBuilder pb = new ProcessBuilder();
            if (direction != null && start.equals("1")){
                pb.command(
                        pythonInterpreter,
                        scriptPath,
                        action,
                        "--direction", direction,
                        "--start", start
                );
            }else {
                pb.command(
                        pythonInterpreter,
                        scriptPath,
                        action,
                        "--start", start
                );
            }

            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }

            exitCode= process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (exitCode == null || !exitCode.equals(correct)){
            throw new Exception("python脚本运行异常");
        }

        System.out.println("脚本执行完毕，退出码：" + exitCode);
        return stringBuffer.toString();
    }


    /**
     * 3.4 控制灯光
     * @param red
     * @param yellow
     * @param green
     * @param brightness
     * @return
     */
    public String ControlLight(Integer red,Integer yellow,Integer green,Integer brightness) throws Exception {
        Integer exitCode = null;
        try {
            String action = "control_light";

            ProcessBuilder pb = new ProcessBuilder(
                    pythonInterpreter,
                    scriptPath,
                    action,
                    "--red", red.toString(),
                    "--yellow", yellow.toString(),
                    "--green", green.toString(),
                    "--brightness", brightness.toString()
            );

            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }

            exitCode = process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (exitCode == null || !exitCode.equals(correct)){
            throw new Exception("python脚本运行异常");
        }
        System.out.println("脚本执行完毕，退出码：" + exitCode);
        return stringBuffer.toString();
    }

    /**
     * 3.5 控制蜂鸣器
     * @param buzzer_on
     * @return
     */
    public String ControlBuzzer(String buzzer_on) throws Exception {
        return ToPythonController("control_buzzer","--red",buzzer_on);
    }

    /**
     * 3.6 推出物料
     * @return
     */
    public String PushMaterial() throws Exception {
        return ToPythonController("push_material");
    }

    /**
     * 3.7 运行传送带
     * @return
     */
    public String RunConveyorBelt() throws Exception {
        return ToPythonController("run_conveyor_belt");
    }

    /**
     * 3.8 设置轴速度
     * @param axis
     * @param speed
     * @return
     */
    public String SetAxisSpeed(String axis,String speed) throws Exception {
        Integer exitCode = null;
        try {
            String action = "set_axis_speed";
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(
                    pythonInterpreter,
                    scriptPath,
                    action,
                    "--axis", axis,
                    "--speed", speed
            );

            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }

            exitCode = process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (exitCode == null || !exitCode.equals(correct)){
            throw new Exception("python脚本运行异常");
        }
        System.out.println("脚本执行完毕，退出码：" + exitCode);

        return stringBuffer.toString();
    }

    /**
     * 3.9 轴回原点
     * @param axis
     * @return
     */
    public String MoveAxisToOrigin(String axis) throws Exception {
        return ToPythonController("move_axis_to_origin","--axis",axis);
    }

    public String MoveAxis(String axis,String direction,String material_action) throws Exception {
        Integer exitCode = null;
        try {
            String action = "control_conveyor_belt";
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(
                    pythonInterpreter,
                    scriptPath,
                    action,
                    "--axis", axis,
                    "--direction", direction,
                    "--material_action",material_action
            );

            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }

            exitCode = process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (exitCode == null || !exitCode.equals(correct)){
            throw new Exception("python脚本运行异常");
        }
        System.out.println("脚本执行完毕，退出码：" + exitCode);

        return stringBuffer.toString();
    }

    /**
     * 3.11 停止轴
     * @param axis
     * @return
     */
    public String StopAxis(String axis) throws Exception {
        return ToPythonController("stop_axis","--axis",axis);
    }

    /**
     *3.12 转换开关
     * @return
     */
    public String ToggleSwitches() throws Exception {
        return ToPythonController("toggle_switches");
    }

    /**
     *3.13 控制轴位置
     * @param x_pulse
     * @param y_pulse
     * @return
     */
    public String ControlAxisPosition(String x_pulse,String y_pulse) throws Exception {
        Integer exitCode = null;
        try {
            String action = "control_conveyor_belt";
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(
                    pythonInterpreter,
                    scriptPath,
                    action,
                    "--x_pulse", x_pulse,
                    "--y_pulse", y_pulse
            );

            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }

            exitCode = process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (exitCode == null || !exitCode.equals(correct)){
            throw new Exception("python脚本运行异常");
        }
        System.out.println("脚本执行完毕，退出码：" + exitCode);
        return stringBuffer.toString();
    }

    /**
     * 3.14 读取轴位置
     * @param axis
     * @return
     */
    public String ReadAxisPosition(String axis) throws Exception {
        return ToPythonController("read_axis_position","--axis",axis);
    }

    /**
     * 3.15 获取传送带状态
     * @return
     */
    public String GetConveyorStatus() throws Exception {
        return ToPythonController("get_conveyor_status");
    }




    public String ToPythonController(String action) throws Exception {
        Integer exitCode = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(
                    pythonInterpreter,
                    scriptPath,
                    action
            );

            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }

            exitCode = process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (exitCode == null || !exitCode.equals(correct)){
            throw new Exception("python脚本运行异常");
        }
        System.out.println("脚本执行完毕，退出码：" + exitCode);

        return stringBuffer.toString();
    }

    public String ToPythonController(String action,String parameter1,String parameter2) throws Exception {
        Integer exitCode = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(
                    pythonInterpreter,
                    scriptPath,
                    action,
                    parameter1,parameter2
            );

            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                stringBuffer.append(line);
            }

            exitCode = process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (exitCode == null || !exitCode.equals(correct)){
            throw new Exception("python脚本运行异常");
        }
        System.out.println("脚本执行完毕，退出码：" + exitCode);
        return stringBuffer.toString();
    }


}